package com.yxt.qmgf.snake.ctrl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yxt.qmgf.snake.vo.ScoreVO;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ScoreManager {
    private static final String SCORE_FILE = "scores.json"; // 积分记录文件
    private static final Gson gson = new Gson();

    // 保存积分记录
    public static void saveScore(ScoreVO score) {
        List<ScoreVO> scores = loadScores(); // 加载现有记录
        scores.add(score); // 添加新记录

        try (FileWriter writer = new FileWriter(SCORE_FILE)) {
            gson.toJson(scores, writer); // 写入文件
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 加载积分记录
    public static List<ScoreVO> loadScores() {
        List<ScoreVO> scores = new ArrayList<>();
        try (FileReader reader = new FileReader(SCORE_FILE)) {
            Type listType = new TypeToken<List<ScoreVO>>() {}.getType();
            scores = gson.fromJson(reader, listType); // 从文件读取
        } catch (IOException e) {
            // 文件不存在时忽略错误
        }
        return scores != null ? scores : new ArrayList<>();
    }
}